package com.dream.app.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dream.app.cache.AppGroupResourceCache;
import com.dream.app.cache.AppResourceCache;
import com.dream.app.service.GroupService;
import com.dream.base.controller.BaseController;
import com.dream.model.app.AppGroup;
import com.dream.model.app.AppPosition;
import com.dream.model.app.AppResource;
import com.dream.utils.annotation.AccessLog;
import com.dream.utils.annotation.AccessToken;
import com.dream.utils.annotation.AccessTokenType;
import com.dream.utils.annotation.SkipAuthority;
import com.dream.utils.hibernate.PagingVO;
import com.dream.utils.log.DreamLogUtils;
import com.dream.vo.app.GroupVO;
import com.dream.vo.base.MvcValidtorResult;
import com.dream.vo.base.ResultType;
import com.google.common.collect.Maps;

/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2013/8/29
 */
@Controller
@RequestMapping(value = "/app/group")
public class AppGroupController extends BaseController{
	
	@Autowired
	private AppResourceCache appResourceCache;
	
	@Autowired
	private GroupService groupService;
	
	@Autowired
	private AppGroupResourceCache appGroupResourceCache;
	
	
	/**
	 * 
	 * @copyright evan
	 * @author evan
	 * @date 2013-9-3
	 * @param userId
	 * @param modify
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value="/detail/{groupId}")
	@AccessLog(module="app/group",content="用戶组详细")
	@AccessToken(AccessTokenType.generate)
	public String  detail(@PathVariable String groupId,Model modelMap){
		
		modelMap.addAttribute("group", appGroupCache.getById(groupId));
		modelMap.addAttribute("myResources", appGroupResourceCache.getMyResources(groupId));
		return "group_add_mod";
	}
	
	@RequestMapping(value = "/init")
	@AccessLog(module="app",content="新增用戶组初始化")
	@AccessToken(AccessTokenType.generate)
	@SkipAuthority
	public String init() {
		
		return "group_add_mod";
	}
	
	/**
	 * 
	 * @copyright evan
	 * @author evan
	 * @date 2013-9-3
	 * @param modelMap
	 * @param userVO
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/add")
	@AccessLog(module="app",content="新增用戶组")
	@AccessToken(AccessTokenType.verify)
	public Map<String, Object> add(@Valid GroupVO groupVO,BindingResult valResult) {
		
		Map<String,Object> result = Maps.newHashMap();
		MvcValidtorResult errors = populateErrors(valResult);
		
		if(valResult.hasErrors()){
			result.put(RESULT_TYPE, ResultType.INPUT.toInteger());
			result.put(RESULT_CONTENT, errors);
			
		}else{
			try{
				if(groupService.existed(groupVO.getId())){
					
					this.addFieldMessage(errors, "id", "err0004");
					result.put(RESULT_TYPE, ResultType.INPUT.toInteger());

				}else{
					groupService.add(groupVO, getUser());
					result.put(RESULT_TYPE,ResultType.SUCCESS.toInteger());
				}
				
			}catch(Exception ex){
				result.put(RESULT_TYPE, ResultType.EXCEPTION.toInteger());
				DreamLogUtils.error(this,"add","add group occured exception", ex);
			}
			
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/exist/{groupId}")
	@AccessLog(module="app/group",content="用戶组存在性检查")
	public Boolean exist(@PathVariable String groupId) {
		
		return groupService.existed(groupId);
	}
	/**
	 * 
	 * @copyright evan
	 * @author evan
	 * @date 2013-9-3
	 * @param modelMap
	 * @param userVO
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/modify")
	@AccessLog(module="app/group",content="修改用戶组")
	@AccessToken(AccessTokenType.verify)
	public Map<String, Object> modify(Model modelMap,@Valid GroupVO groupVO,BindingResult valResult) {
		
		Map<String,Object> result = Maps.newHashMap();
		MvcValidtorResult errors = populateErrors(valResult);
		
		if(valResult.hasErrors()){
			result.put(RESULT_TYPE, ResultType.INPUT.toInteger());
			result.put(RESULT_CONTENT, errors);
			
		}else{
			try{
				groupService.modify(groupVO, getUser());
				result.put(RESULT_TYPE,ResultType.SUCCESS.toInteger());
				appGroupCache.reload();
				appGroupResourceCache.reload(groupVO.getId());
			}catch(Exception ex){
				result.put(RESULT_TYPE, ResultType.EXCEPTION.toInteger());
				DreamLogUtils.error(this,"add","add group occured exception", ex);
			}
		}
		return result;
	}
	
	
	/***
	 * 
	 * @copyright evan
	 * @author evan
	 * @date 2013-9-4
	 * @param modelMap
	 * @param userVO
	 * @param pageVO
	 * @return
	 */
	@RequestMapping(value = "/list")
	@AccessLog(module="app",content="查询用戶组")
	public String list(Model modelMap,GroupVO vo,PagingVO pageVO) {
		
		modelMap.addAttribute("pageVO", groupService.query(vo, pageVO));
		return "app/group/data/group_list_data";
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete/{groupId}")
	@AccessLog(module="app",content="删除用戶组")
	public Boolean groupDelete(@PathVariable String groupId) {
		boolean res = true;
		try {
			groupService.delete(groupId);
			appGroupCache.reload();
			appGroupResourceCache.reload(groupId);
		} catch (Exception ex) {
			res = false;
			DreamLogUtils.error(this, "userDelete","delete user occured exception", ex);
		}
		return res;
	}
	
	@ModelAttribute("resources")
	public Map<String,Map<String,List<AppResource>>> getAllResources(){
		
		return appResourceCache.getAllByModule();
	}
	
	@ModelAttribute("positions")
	public Map<Long,AppPosition> getAllPosition(){
		
		return appPositionCache.getAll();
	}
	
	@ModelAttribute("groups")
	public Map<String,AppGroup> getAllGroup(){
		
		return appGroupCache.getAll();
	}
}
